package com.tupu.util;

import cn.hutool.core.codec.Base64;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.spire.xls.Workbook;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class  FileUtil {

    //ip地址
    public static String IP;

    //ip地址
    public static String Path;

    @Value("${file.ipAddress}")
    public void setIpAddress(String ipAddress){
        IP = ipAddress;
    }

    @Value("${file.filePath}")
    public void setFilePath(String filePath){
        Path = filePath;
    }

    /**
     * csv文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Map<String, Object> importCSV(MultipartFile file) throws IOException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
        Map<String, Object> result = new HashMap<>();
        //获取文件名字
        //String filename = file.getOriginalFilename();
        //log.info("csv文件原名:" + filename);
        //取新名字+时间戳
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //获取文件后缀
        for (int i = 0; i < 4; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        String date = format.format(new Date());
        String newName = date + sb + type;
        //log.info("csv新文件名:" + newName);
        //上传目录
        //File f = new File("/home/csv/");
        File f = new File(Path);
        String path = f.getCanonicalPath();
        //上传至该文件夹下
        file.transferTo(new File(path + "/" + newName));
        //返回地址，输出结果
        String URL = IP + "/api/csv/" + newName;
        result.put("status", "success");
        result.put("file_name", newName);
        result.put("file_path", URL);
        return result;
    }

    /**
     * 将excel文件多sheet 拆分 csv文件
     *
     * @param
     * @return
     * @throws IOException
     */
    public static List<String> cut(String file_path) throws IOException {
        File file = new File(file_path);
        InputStream inputStream;
        ClassPathResource resource = new ClassPathResource(file_path);
        inputStream = resource.getInputStream();
        FileUtils.copyInputStreamToFile(inputStream, file);
        String absolutePath = file.getAbsolutePath();

        List<String> list = new ArrayList<>();
        //拆分导出路径
        //String filePath = "/home/csv/";
        //创建Workbook对象，采用spire
        Workbook wb = new Workbook();
        //路径+文件名
        //加载文件
        //wb.loadFromFile(absolutePath);
        wb.loadFromFile(file_path);
        //声明变量
        Workbook newWb;
        String sheetName;
        //拆分存放路径
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 5; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        //遍历都有sheet
        for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
            //初始化，先删除工作表
            newWb = new Workbook();
            newWb.getWorksheets().clear();
            //复制到新工作表
            newWb.getWorksheets().addCopy(wb.getWorksheets().get(i));
            //获取sheet名称
            sheetName = wb.getWorksheets().get(i).getName();
            //文件名
            String name = sb + "_" + i + ".csv";
            String path = Path + name;
            //保存文件
            //CSVWriter writer = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file_path), "UTF-8"));
            //writer.writeAll(newWb.getWorksheets().);
            //writer.close();
            newWb.saveToFile(path);
            list.add(IP + "/api/csv/" + name);
        }
        return list;
    }

    /**
     * 读取csv文件，导入功能
     *
     * @param file_path
     * @return
     */
    public static List<List<String>> readCsv(String file_path) throws FileNotFoundException, UnsupportedEncodingException, MalformedURLException, URISyntaxException {

        FileInputStream inputStream = new FileInputStream(file_path);
        List<List<String>> list = new ArrayList<>();
        int i = 0;
        CSVReader csvReader = new CSVReaderBuilder(
                new BufferedReader(
                        new InputStreamReader(inputStream, "GB2312"))).build();
        Iterator<String[]> iterator = csvReader.iterator();
        while (iterator.hasNext()) {
            String[] next = iterator.next();
            List<String> stringList = Arrays.asList(next);
            //去除第一行的表头，从第二行开始
            if (i >= 1) {
                List<String> string = new ArrayList<>();
                for (String s : stringList) {
                    if (!s.isEmpty()) {
                        string.add(s);
                    }
                }
                list.add(string);
            }
            i++;
        }
        return list;
    }

    /**
     * 读取csv文件内容
     *
     * @param file_path
     * @return
     * @throws FileNotFoundException
     * @throws UnsupportedEncodingException
     */
    public static List<List<String>> readCsvLine(String file_path) throws FileNotFoundException, UnsupportedEncodingException {

        List<List<String>> list = new ArrayList<>();

        FileInputStream inputStream = new FileInputStream(file_path);

        int i = 0;
        CSVReader csvReader = new CSVReaderBuilder(
                new BufferedReader(
                        new InputStreamReader(inputStream, "utf-8"))).build();
        Iterator<String[]> iterator = csvReader.iterator();
        while (iterator.hasNext()) {
            String[] next = iterator.next();
            List<String> stringList = Arrays.asList(next);
            //读取第一行和第二行
            if (i >= 0 && i < 2) {
                List<String> string = new ArrayList<>();
                for (String s : stringList) {
                    if (!s.isEmpty()) {
                        string.add(s);
                    }
                }
                list.add(string);
            }
            i++;
        }
        return list;
    }

    /**
     * 读取word内表格数据 仅支持docx格式
     *
     * @param filePath 文件路径
     * @return list 如要取第五行第三列数据 则=list.get(4).get(2)
     */
    public static List<List<String>> readWordTable(String filePath) throws Exception {
        List listAll = new ArrayList();
        FileInputStream in = new FileInputStream(filePath);//载入文档
        // 处理docx格式 即office2007以后版本
        if (filePath.toLowerCase().endsWith("docx")) {
            //word 2007 图片不会被读取， 表格中的数据会被放在字符串的最后
            XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
            Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
            // 设置需要读取的表格  set是设置需要读取的第几个表格，total是文件中表格的总数
            //int set = 1, total = 2;
            //int num = set;
            // 过滤前面不需要的表格
              /*  for (int i = 0; i < set-1; i++) {
                    it.hasNext();
                    it.next();
                }*/
            while (it.hasNext()) {
                XWPFTable table = it.next();
                // System.out.println("这是第" + num + "个表的数据");
                List<XWPFTableRow> rows = table.getRows();
                //读取每一行数据
                for (int i = 0; i < rows.size(); i++) {
                    List list = new ArrayList();
                    XWPFTableRow row = rows.get(i);
                    //读取每一列数据
                    List<XWPFTableCell> cells = row.getTableCells();
                    for (int j = 0; j < cells.size(); j++) {
                        Map<Integer, String> map = new HashMap();
                        XWPFTableCell cell = cells.get(j);
                        map.put(j + 1, cell.getText());
                        list.add(cell.getText());
                        //输出当前的单元格的数据
                        //System.out.print("第" + (i + 1) + "行：" + "第" + (j + 1) + "列：" + cell.getText() + "\t");
                    }
                    listAll.add(list);
                }
            }
        } else {
            throw new Exception("请上传docx格式的文档！");
        }
        return listAll;
    }

    /**
     * 下载返回输出流
     *
     * @param path
     * @param response
     */
    public static void download(String path, HttpServletResponse response) throws IOException {
        File file = new File(path);
        FileInputStream fis = new FileInputStream(file);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        BufferedInputStream bis = new BufferedInputStream(fis);
        ServletOutputStream sos = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            sos.write(buffer, 0, len);
        }
        sos.flush();
        sos.close();
        bis.close();
        fis.close();
    }

    public static void downloadWord(String fileName, String fileContent, HttpServletResponse response) throws IOException {
        byte[] bytes = Base64.decode(fileContent);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        ServletOutputStream sos = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            sos.write(buffer, 0, len);
        }
        sos.flush();
        sos.close();
        bis.close();
    }

    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    public static void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        //设置内容类型
        response.setContentType("application/vnd.vnd.ms-excel");
        //设置编码格式
        response.setCharacterEncoding("utf-8");
        //设置导出文件名称（避免乱码）
        String fileName = URLEncoder.encode(rawFileName.concat(".xlsx"), "UTF-8");
        // 设置响应头
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
    }
}